package com.miyake.loveviewweb.server.controller;

import javax.servlet.http.HttpServletResponse;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.controller.upload.FileItem;
import org.slim3.datastore.Datastore;

import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.miyake.loveviewweb.server.DataModelManager;
import com.miyake.loveviewweb.server.meta.UserModelMeta;
import com.miyake.loveviewweb.server.service.MyUserKey;
import com.miyake.loveviewweb.shared.model.DataModel;
import com.miyake.loveviewweb.shared.model.FolderModel;
import com.miyake.loveviewweb.shared.model.UserModel;

public class UploadController extends Controller {

    @Override
    public Navigation run() throws Exception {
        HttpServletResponse resp = this.response;
        
        if (this.isPost()) {
            
            UserService userService = UserServiceFactory.getUserService();
            User u = userService.getCurrentUser();
            UserModelMeta e = UserModelMeta.get();
            UserModel userModel = Datastore.query(e).filter(e.userID.equal(u.getUserId())).asSingle();
            Key key = userModel.getSelectedItem();
            
            FolderModel folderModel = Datastore.get(FolderModel.class, key);
                        
            FileItem formFile = requestScope("fileupload");

            DataModel dataModel = new DataModel();
            dataModel.setName(formFile.getShortFileName());
            dataModel.setFolder(folderModel.getKey());
            dataModel.setParsed(false);
            dataModel.setSourceType(DataModel.SourceType.File);         
            dataModel.setOwner(MyUserKey.get());
            
            if (formFile.getContentType().contains("image")) {
                dataModel.setDataType(DataModel.DataType.Image);
                new DataModelManager().storeImage(dataModel, formFile.getData(),formFile.getContentType());
            }
            else if (formFile.getContentType().contains("audio")){
                dataModel.setDataType(DataModel.DataType.Audio);
            }
            else {
                dataModel.setDataType(DataModel.DataType.ValueArray);
                new DataModelManager().storeUnknow(dataModel, formFile.getData(),formFile.getContentType());
            }
            
            resp.setContentType("text/html");
            resp.getWriter().print("<b>OK</b>");
            resp.getWriter().flush();
            resp.getWriter().close();
         //   return null;//redirect(basePath);
        }
        else {
            
        }
        //return forward("Upload.jsp");

        return null;//redirect("");
    }

}
